<style scoped>
.ivu-form-item {
    margin-bottom: 5px;
}
.demo-upload-list{
        display: inline-block;
        width: 75px;
        height: 75px;
        text-align: center;
        line-height: 75px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
<template>
  <div>
    <Card>
      <div  class="search-con search-con-top">
        <Button style="margin-right: 10px;" type="primary" @click="addOrUpdate = true">添加</Button>
        <Button style="margin-right: 10px;" type="primary" @click="exportExcel">导出为Csv文件</Button>
        <Select v-model="searchKey" class="search-col" placeholder="请选择检索项">
          <Option v-for="item in columns" v-if="item.key !== 'handle'" :value="item.key" :key="item.key">{{ item.title }}</Option>
        </Select>
        <Input clearable placeholder="输入关键字搜索" class="search-input" v-model="searchValue"/>
        <Button @click="handleSearch" class="search-btn" type="primary"><Icon type="search"/>&nbsp;&nbsp;搜索</Button>
      </div>
      
      <tables :height="innerHeight - 250" ref="tables" search-place="top" v-model="tableData" :columns="columns" :loading="tabLoading"/>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
            <Page :total="total" size="small" show-elevator show-sizer @on-change="changePage" @on-page-size-change="pageSizeChange"/>
        </div>
      </div>
    </Card>
    <Modal v-model="addOrUpdate" :title="modelTitle" @on-ok="ok" @on-cancel="cancel" :mask-closable="false" width="1200">
        <Form ref="addFrom" :model="addFrom" :label-width="100">
            <Row>
                <Col span="16">
                <!-- topicContent -->
                  <editor ref="editor" :value="addFrom.topicContent" @on-change="handleChange" />
                </Col>
                <Col span="8">
                  <Row>
                    <Col span="24">
                        <FormItem label="文章编码" prop="topicCode" :rules="{required: true, message: '请填写文章编码', trigger: 'blur'}">
                            <Input v-model="addFrom.topicCode" placeholder="请填写文章编码"></Input>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="文章标题" prop="topicName" :rules="{required: true, message: '请填写文章标题', trigger: 'blur'}">
                            <Input v-model="addFrom.topicName" placeholder="填写文章标题"></Input>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="文章作者" prop="topicAuthor" :rules="{required: true, message: '请填写文章作者', trigger: 'blur'}">
                            <Input v-model="addFrom.topicAuthor" placeholder="请填写文章作者"></Input>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="是否置顶" prop="top">
                            <Checkbox v-model="addFrom.top"></Checkbox>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="是否加精" prop="essence">
                            <Checkbox v-model="addFrom.essence"></Checkbox>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="浏览量" prop="lookNumber" >
                            <Input v-model="addFrom.lookNumber" placeholder="填写浏览量"></Input>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="评论量" prop="scoreNum" >
                            <Input v-model="addFrom.scoreNum" placeholder="填写评论量"></Input>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="标签" prop="label" >
                            <Input v-model="addFrom.label" placeholder="填写标签"></Input>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="展示图片" prop="pic" >
                            <div class="demo-upload-list" v-for="item in pic.uploadList">
                                <template v-if="item.status === 'finished'">
                                    <img :src="item.url">
                                    <div class="demo-upload-list-cover">
                                        <Icon type="ios-copy" v-clipboard="clipOptions(item.url)"></Icon>
                                        <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                    </div>
                                </template>
                                <template v-else>
                                    <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                                </template>
                            </div>
                            <Upload
                                ref="upload"
                                :show-upload-list="false"
                                :default-file-list="pic.defaultList"
                                :on-success="handleSuccess2"
                                :data="{uploadType:'topic',resultType:''}"
                                :format="['jpg','jpeg','png']"
                                :max-size="2048"
                                multiple
                                type="drag"
                                action="https://www.dxbeibei.com/wx.minproject.xiong.application/file/comm/msg/fileUpload.do"
                                style="display: inline-block;width:58px;">
                                <div style="width: 58px;height:58px;line-height: 58px;">
                                    <Icon type="ios-camera" size="20"></Icon>
                                </div>
                            </Upload>
                        </FormItem>
                    </Col>
                </Row>
                </Col>
            </Row>
        </Form>
        <Modal title="View Image" v-model="pic.visible">
            <img :src="'https://www.dxbeibei.com/wx.minproject.xiong.html/' + pic.imgName" v-if="pic.visible" style="width: 100%">
        </Modal>
    </Modal>
  </div>
  
</template>

<script>
import Tables from '_c/tables'
import { tablePublicRequest } from '@/api/data'
import Editor from '_c/editor'
export default {
  name: 'tables_page',
  components: {
    Tables,Editor
  },
  data () {
    return {
      actionUrl:{
        "BATCH":"smc/topic/NewTopics/saveNewTopics.json",
  		  "QRY":"smc/topic/NewTopics/queryNewTopics.json",
  		  "ADD":"smc/topic/NewTopics/addNewTopics.do",
  		  "DEL":"smc/topic/NewTopics/delNewTopics.do",
  		  "UPD":"smc/topic/NewTopics/updNewTopics.do",
  		  "LKUP":"smc/topic/NewTopics/lookupNewTopics.json",
  		  "LST":"smc/topic/NewTopics/listNewTopics.json",
  		  "FIND":"smc/topic/NewTopics/findNewTopics.json"
      },   
      innerHeight:document.body.clientHeight, 
      pic:{
        defaultList: [],
        imgName: '',
        visible: false,
        uploadList: []
      },
      addOrUpdate: false,
      modelTitle:"新增",
      searchKey:"",
      searchValue:"",
      page:1,
      pageSize:10,
      total:0,
      search:{},
      addFrom:{},
      tabLoading:true,
      columns: [
      //{field:"pic",type:"text",display:"图片"   },	
        {title: '文章编码', key: 'topicCode', sortable: true,width:120},
        {title: '文章标题', key: 'topicName', sortable: true,width:120},
        {title: '文章作者', key: 'topicAuthor', sortable: true,width:120},
        {title: '是否置顶', key: 'top', sortable: true,width:120},
        {title: '是否加精', key: 'essence', sortable: true,width:120},
        {title: '浏览量', key: 'lookNumber', sortable: true,width:120},
        {title: '评论量', key: 'scoreNum', sortable: true,width:120},
        {title: '标签', key: 'label', sortable: true,width:120},
        {
          title: '操作',
          key: 'handle',
          fixed:'left',
          width:80,
          button: [
            (h, params, vm) => {
              return h('Button', {
                  props: {
                    type: 'text',
                    ghost: true
                  },
                  attrs:{
                    style:"padding: 5px 0;"
                  },
                  on: {
                    'click': () => {
                      tablePublicRequest(this.actionUrl.FIND,{"id":params.row.topicId}).then(res => {
                        let data = res.data;
                        if(data.success){
                          this.addFrom = data.data || {};
                          this.addOrUpdate = true;
                          var zpic = this.addFrom.pic;
                          this.$refs.editor.setHtml(this.addFrom.topicContent);
                          if(zpic && zpic.length > 0){
                              let zpics = zpic.split(",");
                              let dlist = [];
                              for(var i=0;i<zpics.length;i++){
                                  dlist.push({status:'finished',name:zpics[i],url: `https://www.dxbeibei.com/wx.minproject.xiong.html/${zpics[i]}`});
                              }
                              this.$refs.upload.fileList = dlist;
                              this.pic={
                                    defaultList: dlist,
                                    imgName: '',
                                    visible: false,
                                    uploadList: dlist
                                }
                          }
                          
                        }
                      })
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'ios-create',
                      size: 18,
                      color: '#000000'
                    }
                  })
              ])
            },
            (h, params, vm) => {
              return h('Poptip', {
                props: {
                  confirm: true,
                  title: '你确定要删除吗?',
                  transfer:true
                },
                on: {
                  'on-ok': () => {
                    tablePublicRequest(this.actionUrl.DEL,{"id":params.row.topicId}).then(res => {
                      let data = res.data;
                      if(data.success){
                        this.$Message.info('删除成功！');
                        this.handleSearch();
                        this.pic={
                            defaultList: [],
                            imgName: '',
                            visible: false,
                            uploadList: []
                        }
                      }
                    })
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'text',
                    ghost: true
                  },
                  attrs:{
                    style:"padding: 5px 0;"
                  },
                }, [
                  h('Icon', {
                    props: {
                      type: 'md-trash',
                      size: 18,
                      color: '#000000'
                    }
                  })
                ])
              ])
            }
          ]
        }
      ],
      tableData: []
    }
  },
  methods: {
    handleChange (html, text) {
      this.addFrom.topicContent = html;
      console.log(html);
      console.log(text);
    },
    clipOptions(url) {
      return {
        value: url,
        success: (e) => {
          this.$Message.success('复制成功')
        },
        error: () => {
          this.$Message.error('复制失败')
        }
      }
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    ok () {
      delete this.addFrom.createdAt;
      delete this.addFrom.lastedUpdAt;
      let url = this.addFrom.topicId?this.actionUrl.UPD:this.actionUrl.ADD;
      this.modelTitle = this.addFrom.topicId?"修改":"新增";
      let pics = [];
      for(var i=0;i<this.pic.uploadList.length;i++){
            pics.push(this.pic.uploadList[i].name);
      }
      this.addFrom.pic = pics.toString();
      tablePublicRequest(url,this.addFrom).then(res => {
        let data = res.data;
        if(data.success){
          this.$Message.info(`${this.modelTitle}成功！`);
          this.handleSearch();
          this.addFrom = {};
          this.$refs.editor.setHtml('');
          this.pic={
            defaultList: [],
            imgName: '',
            visible: false,
            uploadList: []
          }
        }
      })
    },
    cancel () {
        this.addFrom = {};
        this.$refs.editor.setHtml('');
        this.pic={
            defaultList: [],
            imgName: '',
            visible: false,
            uploadList: []
        }
    },
    changePage (data) {
      this.page = data;
      this.handleSearch();
    },
    pageSizeChange(data){
      this.pageSize = data;
      this.handleSearch();
    },
    handleSearch(){
      this.search = {page: this.page,pagesize: this.pageSize};
      this.search.searchRules=`[{"op":"contains","field":"${this.searchKey}","value":"${this.searchValue}","type":"text"}]`;
      this.setTableData(this.search);
    },
    setTableData(params){
      this.tabLoading = true;
      tablePublicRequest(this.actionUrl.QRY,params).then(res => {
        let data = res.data;
        if(data.success){
          let tdata = data.data;
          this.total = tdata.total;
          this.tabLoading = false;
          this.tableData = tdata.rows||[];
        }
      })
    },
    handleSuccess(res, file){
      this.$Message.info(res.msg);
      this.addFrom.attribute1 = res.path;
    },
    handleError(res, file){
      this.$Message.info(res.msg);
    },
    handleView (name) {
        this.pic.imgName = name;
        this.pic.visible = true;
    },
    handleRemove (file) {
        let k=-1;
        for(var i=0;i<this.pic.uploadList.length;i++){
            if(file.name == this.pic.uploadList[i].name){
                k = i;
                break;
            }
        }
        this.pic.uploadList.splice(k, 1);

        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess2 (res, file) {
      this.$Message.info(res.msg);
        
        this.pic.uploadList.push({status:'finished',name:res.path,url: `https://www.dxbeibei.com/wx.minproject.xiong.html/${res.path}`});
        file.url = `https://www.dxbeibei.com/wx.minproject.xiong.html/${res.path}`;
        file.name = res.path;
    }
  },
  mounted () {
    this.setTableData({page: this.page,pagesize: this.pageSize});
    // this.pic.uploadList = this.$refs.upload.fileList;
    console.log(this.$refs.editor.customConfig);
  }
}
</script>


